import { defineStore } from 'pinia';
import { ref } from 'vue';
import { login as doLogin } from '@/api';
import { setToken, clearToken, getToken } from '@/utils';
import { useAppid } from '@/hooks';

export const useUserStore = defineStore('user', () => {
  const user = ref<API.User>();
  const isLogin = ref(!!getToken());

  const launchOptions = uni.getLaunchOptionsSync();

  async function login() {
    try {
      const { code, anonymousCode } = await uni.login({});
      const { data } = await doLogin(code, useAppid(), anonymousCode ?? '');
      setToken(data.access_token);
      isLogin.value = true;
      user.value = data;
      uni.$emit('login');
    } catch (e: any) {
      uni.showToast({
        icon: 'none',
        title: '登录授权失败',
        duration: 1500,
      });
    }
  }

  !isLogin.value && login();

  return {
    user,
    login,
    isLogin,
  };
});
